package com.ysu.shop.handler;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ysu.shop.controller.RoleController;
import com.ysu.shop.exception.UserNoLoginException;
import com.ysu.shop.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @description ：拦截器去获取token并验证token
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object object) throws Exception {
        /** 地址过滤 */
        String uri = request.getRequestURI();
        log.info("url: "+uri);
        if (uri.endsWith("/login") || uri.endsWith("/error")||uri.startsWith("/shop")) {
            return true;
        }
        String token = request.getHeader("Authorization");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        if (token == null) {
            throw new UserNoLoginException();
        }
        JwtUtil.isExpire(token);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o,
                                Exception e) throws Exception {
    }
}